package com.thtfpc.demo;

import com.thtfpc.discovery.ScreenScanner;
import com.thtfpc.utility.InetUtil;
import com.thtfpc.ssdp.SSDPDevice;
import com.thtfpc.utility.InputUtil;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * Player服务扫描器演示，用来扫描ScreenPlayer设备
 */
public class DemoForScanner implements ScreenScanner.ScannerCallback {

    static Logger logger = Logger.getLogger(DemoForScanner.class.getSimpleName());
    protected ScreenScanner screenScanner;

    public DemoForScanner() {
        String address = "127.0.0.1";
        try {
            address = InetUtil.getLocalHostAddress().getHostAddress();
        }
        catch (Exception ex) {
        }
        /*
         ScreenScanner  参数1:rtsp播放地址 参数2 事件回调
         */
        screenScanner = new ScreenScanner("rtmp://202.69.69.180:443/webcast/bshdlive-pc", this);
    }

    public void start() throws IOException {
        //启动服务
        screenScanner.start();
        //开始搜索设备
        //screenScanner.startSearch();
    }

    public void stop() throws IOException {
        //停止服务
        screenScanner.stop();
    }

    public void search() {
        screenScanner.startSearch();
    }

    public void stopSearch() {
        screenScanner.stopSearch();
    }

    /*
    search调用后，如果一个新设备上线被发现被回调
    */
    @Override
    public void onDeviceOnlined(SSDPDevice device) {
        //device对象中保存了找到的PlayerEndPoint的信息
        logger.info("[设备上线] onDeviceOnlined:" + device);
        //停止搜索；
        // 如果UI界面程序，stopSearch一般由用户发起停止搜索
        //screenScanner.stopSearch();
        //向这个Player设备发起链接协商;
        // 如果是UI程序，发起链接一般由用户发起
        screenScanner.requestRender(device);
    }

    @Override
    public void onDeviceOfflined(SSDPDevice device) {

    }

    /*
        当与ScreenPlayer握手完成后被回调，如果result.errorcode==0
        一般来说对方Player已经开始播放
         */
    @Override
    public void onRenderResult(ScreenScanner.RenderResult result) {
        logger.info("[播放结果] onRenderResult:" + result);
    }

    public static void main(String[] args) throws IOException {
        DemoForScanner demoForScanner = new DemoForScanner();
        demoForScanner.start();
        System.out.println("type \"start search\" to search, \"stop search\" to stop.");
        //输入阻塞
        InputUtil.quitFor("exit", new InputUtil.InputListener() {
            @Override
            public void onUserTypeString(String input) {
                switch (input) {
                    case "start search":
                        demoForScanner.search();
                        break;

                    case "stop search":
                        demoForScanner.stopSearch();
                        break;
                    default:
                        System.out.println("type \"exit\" for quit");
                        break;
                }
            }
        });
        demoForScanner.stop();
    }
}
